<template>
	<section>
		<!--工具条 +关键字查询+新增-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字查询"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery" icon="el-icon-zoom-in">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" icon="el-icon-circle-plus">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="exportData" icon="el-icon-sold-out" >导出</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 默认name="file" -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/shop/importExcel"
                     list-type="text">
            <el-button type="warning"  icon="el-icon-sell" >导入</el-button>
          </el-upload>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表数据-->
		<el-table :data="shops" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" :row-key="getKey"  ref="multiTable" style="width: 100%;">
			<el-table-column type="selection" width="55" :reserve-selection="true">
			</el-table-column>
			<el-table-column type="index" label="序号"width="60">
			</el-table-column>
			<el-table-column prop="name" label="店铺名称" width="100" sortable>
			</el-table-column>
			<el-table-column prop="tel" label="店铺座机" width="150"  sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="入驻时间" width="150" >
			</el-table-column>
			<el-table-column prop="state" label="店铺状态" width="100" >
        <template scope="scope" >
          <span v-if="scope.row.state==1" style="color: blue">待审核</span>
          <span v-if="scope.row.state==2" style="color: magenta" >待激活</span>
          <span v-if="scope.row.state==3" style="color: lime" >激活成功</span>
          <span v-if="scope.row.state==4" style="color: brown">驳回</span>
        </template>
			</el-table-column>
			<el-table-column prop="address"  label="店铺地址" width="230" >
			</el-table-column>

      <el-table-column prop="logo" label="店铺Logo" width="150" sortable>
        <template scope="scope">
          <el-image  :src="imgPrefix + scope.row.logo.split(',')[0]"
                     :preview-src-list="[imgPrefix + scope.row.logo]" width="50px">
          </el-image>
        </template>
      </el-table-column>

			<el-table-column prop="admin.username" label="店铺管理员"  width="150" >
			</el-table-column>

			<el-table-column label="操作">
				<template scope="scope">
          <el-button type="primary" size="medium" :disabled="scope.row.state!=1"
                     @click="handleProcess(scope.$index, scope.row)"
                      icon="el-icon-thumb">人工审核</el-button>
					<el-button type="warning" size="medium"  @click="handleEdit(scope.$index, scope.row)"
                     icon="el-icon-edit-outline">编辑</el-button>
					<el-button type="danger"  size="medium"  @click="handleDel(scope.$index, scope.row)"
                     icon="el-icon-delete">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条+批量删除+分页栏-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-finished">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage"
                     style="float:right;"  >
			</el-pagination>
		</el-col>

		<!--新增+编辑界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false"
               :destroy-on-close="true">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm" class="login-container">
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入店铺名称" clearable auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="店铺电话" prop="tel">
					<el-input v-model="saveForm.tel" placeholder="请输入店铺电话" clearable auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="店铺地址" prop="address">
          <el-input v-model="saveForm.address" placeholder="请输入店铺地址" clearable auto-complete="off" >
            <template #suffix>
              <el-button size="small" type="primary" @click="selectAdrress" icon="el-icon-location">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="店铺状态" prop="state">
          <el-radio-group v-model="saveForm.state">
            <el-radio :label="1"border >待审核</el-radio>
            <el-radio :label="2"border >待激活</el-radio>
            <el-radio :label="3"border >激活成功</el-radio>
            <el-radio :label="4"border >驳回</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item  label="店铺Logo" prop="logo">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="管理员"  prop="adminId">
          <el-select v-model="saveForm.adminId" clearable placeholder="请选择管理员">
            <el-option v-for ="item in employees"
                       :label="item.username"
                       :value="item.id"
                       clearable>
              <span style="float: left">{{ item.username }} </span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false" icon="el-icon-close">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading" icon="el-icon-check">提交</el-button>
			</div>
		</el-dialog>



    <!--百度地图-->
    <div class="app-container">
    <el-dialog
        title="选择地址"
        :visible.sync="dialogVisable"
        width="30%">
      <baidu-map :center="{lng: 104.06, lat: 30.67}" :zoom="11">
        <bm-view class="map"></bm-view>
        <bm-control :offset="{width: '10px', height: '10px'}">
          <bm-auto-complete v-model="keyword2" :sugStyle="{zIndex: 2100}">
            <div style="margin-bottom:10px">
              <input id="searchInput" type="text"  placeholder="请输入关键字" class="searchinput"/>
              <el-button type="success" @click="selectAddressConfirm">确定</el-button>
            </div>
          </bm-auto-complete>
        </bm-control>
        <!--   推荐地址     -->
        <bm-local-search :keyword="keyword2" :auto-viewport="true"  @dblclick="rowDrawerClick">
        </bm-local-search>
      </baidu-map>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisable=false">取 消</el-button>
        <el-button type="primary" @click="dialogVisable=false">确 定</el-button>
      </span>
    </el-dialog>
    </div>

    <!-- 审核模态框 -->
    <el-dialog :title="title" :visible.sync="shopAuditVisible" :close-on-click-modal="false"  >
      <el-form :model="shopAuditLog" label-width="80px"  ref="shopAuditLogForm" >
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="shopAuditLog.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="shopAuditVisible = false">取消</el-button>
        <el-button type="success" @click.native="auditPass">通过</el-button>
        <el-button type="warning" @click.native="auditReject">驳回</el-button>
      </div>
    </el-dialog>

  </section>


</template>
<script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=l6s7T0rlLNctPDmwhN1lYSf1On66gYxL"></script>

<script>

	export default {
		data() {
			return {
        //1.列表显示图片的前缀
        imgPrefix: "http://123.207.27.208",
        //文件上传相关数据
        fileList: [],


			  //1.分页列表展示的相关数据
        shops: [],   //列表数据
        listLoading: false,//关闭加载框
        pageSize:5,        //当前页数
        currentPage:1,     //当前页
        totals:0,          //总条数

        //2.关键字查询
        keyword:'',

        //百度地图相关数据：
        dialogVisable:false,
        keyword2:'',   //关键字重新 百度地图


        //3.新增/修改
        saveFormVisible: false,//新增/编辑界面是否显示
        title:'',             //新增/修改各自变换标题
        saveForm: {           //新增/修改模型数据
          id: null,
          name: '',
          tel: '',
          registerTime: '',
          state: '',
          address: '',
          logo: '',
          adminId: null,
        },
        saveLoading: false,     //保存的加载框 - 默认不显示

        //4.批量删除
        sels: [],//列表选中列

        //6.查询店铺管理员
        employees:{},

        //7.校验表单项里面的数据u
        saveFormRules: {
          name: [
            { required: true, message: '请输入店铺名称', trigger: 'blur' },
            { required: true, message: '请输入店铺名称', trigger: 'change' }
          ],
          tel: [
            { required: true, message: '请输入店铺号码', trigger: 'blur' },
            { required: true, message: '请输入店铺号码', trigger: 'change' }
          ]
        },

        //8.审核模态框
        shopAuditVisible: false,
        //9.编辑界面数据
        shopAuditLog: {
          shopId: null,
          note:''
        },

			}
		},
		methods: {

		  //导出数据
      exportData(){
        //this.$router.push({ path: '/register' });
        location.href="http://localhost:8080/shop/export";
      },


      //1.获取用户列表---分页
      getShops() {
        let para = {
          pageSize: this.pageSize,        //当前的页数
          currentPage: this.currentPage,  //当前页
          keyword: this.keyword,          //关键字查询
        };
        this.listLoading = true ;         //打开加载框
        this.$http.post("/shop",para).then(res=>{
          this.shops=res.data.data; //给模型数据赋值
          this.totals=res.data.totals;    //计算总条数
          this.listLoading = false;       //关闭加载框
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后再试【400,404】")
        })

      },

      //2.点击分页实现
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getShops();
      },

      //3.高级查询
      keywordQuery(){
        this.currentPage = 1;
        this.getShops();
      },

      //4.显示新增界面
      handleAdd: function () {
        this.saveFormVisible = true;
        this.title="新增",
        //重置from表单
        this.saveForm = {
          id: null,
          name: '',
          tel: '',
          registerTime: '',
          state: 1,//默认待激活
          address: '',
          logo: '',
          adminId: null,
        };
        //查询店铺管理员
        this.getEmployees();

        //清空fileList - 页面不显示图片
        this.fileList=[];
      },

      //5.显示修改界面
      handleEdit: function (index, row) {
        this.title="修改";
        //弹出对话框
        this.saveFormVisible = true;
        //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
        this.saveForm = Object.assign({}, row);
        //查询店铺管理员();
        this.getEmployees();

        //图片上传的处理fileList
        this.fileList=[];
        if(this.saveForm.logo){
          // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
          var arr = this.saveForm.logo.split(",");
          for (let i = 0; i < arr.length ; i++) {
            var url = arr[i]
            this.fileList.push({"url":"http://123.207.27.208"+url});
          }
        }
      },

      //6..删除功能逻辑
      handleDel: function (index, row) {
        //elementUi提供确认框 - 点确定之后执行then里面的代码，点击取消执行catch中的逻辑
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //显示加载框
          this.$http.delete("/shop/"+row.id).then(res=>{
            this.listLoading = false; //关闭加载框
            if(res.data.success){
              this.$message.success("删除成功"); //提示成功消息

              //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
              var totalPage = Math.ceil(this.totals/this.pageSize); //总页数 = 最后一页
              //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage--;
              }
              this.getShops();
            }else{
              this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
            }
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试!!![400,404]");
          })
        }).catch(() => {
          this.$message.info("已取消操作");
          this.$refs.multiTable.clearSelection();
        });
      },

      //7.批量删除
      selsChange: function (sels) {
        this.sels = sels;
      },

      //7.跨页批量删除
      getKey(row){
        return row.id;},

      //7.批量删除逻辑
      batchRemove: function () {
        //获取数组中每一个对象的id 并形成新的数组
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认批量删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //显示加载框
          this.$http.patch("/shop",ids).then(res=>{
            this.listLoading = false; //隐藏加载框
            if(res.data.success){ //操作成功
              this.$message.success("批量删除成功"); //提示成功消息
              //清空批量删除的事件
              this.$refs.multiTable.clearSelection();
              //批量删除后---当前页值为1
              this.currentPage=1;
              this.getShops();
            }else{ //操作失败
              this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
            }
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试!!![400,404]");
          })
        }).catch(() => {
          this.$message.info("已取消操作");

        });
      },

      //8.提交新增表单数据   点击保存提交数据到后端
      saveSubmit: function () {
        //表单验证：表单项中任何一个验证不通过，都不能点击提交
        //所有的ref中名称为saveForm的表单
        this.$refs.saveForm.validate((valid) => {
          if (valid) { //表单验证通过 => 每一个表单项都通过了
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true; //显示加载框
              let para = Object.assign({}, this.saveForm);

              this.$http.put("/shop",para).then(res=>{
                this.saveLoading = false;  //关闭加载框
                this.saveFormVisible = false; //关闭对话框
                if(res.data.success){
                  this.$message.success(this.title+" : 操作成功"); //提示成功消息
                  this.getShops();    //重新加载新列表的数据
                }else{
                  //this.$message.error("系统繁忙，请稍后重试!!![500]");
                  //打印后端的错误信息
                  this.$message.error(res.data.message);
                }
              }).catch(res=>{
                this.saveLoading = false;  //关闭加载框
                this.saveFormVisible = false; //关闭对话框
                this.$message.error("系统繁忙，请稍后重试!!![400,404]");
              })
            });
          }
        });
      },
      //9.文件上传成功之后的回调
      //文件上传的业务逻辑：上传一次，就执行一次
      handleSuccess(response, file, fileList){
        var url = response.resultObj; // /group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
        //1.处理resource：添加和修改都要考虑
        if(this.saveForm.logo){
          this.saveForm.logo = this.saveForm.logo+","+url;
        }else{
          this.saveForm.logo = url;
        }

        //2.处理fileList
        this.fileList=[];
        if(this.saveForm.logo){
          // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
          var arr = this.saveForm.logo.split(",");
          for (let i = 0; i < arr.length ; i++) {
            var url = arr[i]
            this.fileList.push({"url":"http://123.207.27.208"+url});
          }
        }
      },

      //10.文件删除的业务逻辑
      handleRemove(file, fileList) {
        // console.log(file);
        var filePath =file.url; //http://123.207.27.208/group1/M00/02/B0/CgAIC2Nx69eAAFo6AA5Kwha33uA410.gif
        filePath = filePath.substring(filePath.indexOf("/group1")); // /group1/M00/02/B0/CgAIC2Nx69eAAFo6AA5Kwha33uA410.gif

        //1.在文件服务器中删除该图片
        this.$http.delete("/fastDfs?path="+filePath).then(res=>{
          if(res.data.success){
            this.$message({
              message: '删除成功!',
              type: 'success'
            });
          }else{
            this.$message({
              message: '删除失败!',
              type: 'error'
            });
          }
        })
        //2.处理logo：假如logo="url1,url2,url3,url4",现在删除一张图片url2。logo="url1,url3,url4"
        if(this.saveForm.logo){
          var arr = this.saveForm.logo.split(",");
          for (let i = 0; i < arr.length; i++) {
            var url = arr[i];
            if(url == filePath){ //找到了删除的图片了
              arr.splice(i,1);
              break;
            }
          }
          this.saveForm.logo = arr.join(",");
        }

        //3.处理fileList
        this.fileList=[];
        if(this.saveForm.logo){
          // 数组中每一个数据：/group1/M00/02/74/CgAIC2Ng84OAHp_6AAAKeULGgAs198.png
          var arr = this.saveForm.logo.split(",");
          for (let i = 0; i < arr.length ; i++) {
            var url = arr[i]
            this.fileList.push({"url":"http://123.207.27.208"+url});
          }
        }
      },

      //13.查询店铺管理员
      getEmployees() {
        this.$http.get("/employee").then(res => {
          if (res) {
            this.employees = res.data; //查询部门管理员
          }
        })
      },

      //14.人工自能审核功能
      handleProcess(index,row){
        this.title="人工审核店铺";
        //清空批注历史记录
        this.shopAuditLog= {
          shopId: null,
          note:''
        }
        //赋值店铺Id
        this.shopAuditLog.shopId = row.id;
        //显示审核对话框
        this.shopAuditVisible = true;
      },
      //15.审核驳回
      auditReject(){
        this.$http.post("/shop/audit/reject",this.shopAuditLog).then(res=>{
          if (res.data.success){
            this.$message.success( "驳回成功"); //提示成功消息
          }else {
            //this.$message.error( "驳回失败"); //提示驳回失败
            //打印后端的错误信息
            this.$message.error(res.data.message);
          }
          this.shopAuditVisible = false;
          this.getShops();//重新加载页面
        }).catch(res=>{
          this.$message.error( "驳回失败"); //提示驳回失败
        })
      },
      //16.审核通过
      auditPass(){
        this.$http.post("/shop/audit/pass",this.shopAuditLog).then(res=>{
          if (res.data.success){
            this.$message.success( "审核通过"); //提示成功消息
          }else {
            //this.$message.error( "审核失败"); //提示审核失败
            this.$message.error(res.data.message);
          }
          this.shopAuditVisible = false;
          this.getShops();//重新加载页面
        }).catch(res=>{
          this.$message.error( "审核失败"); //提示审核失败
        })
      },

      //百度地址的业务逻辑
      selectAddressConfirm(){
        //获取值搜索框值,设置给地址
        var searchInputV=document.getElementById("searchInput").value;
        this.saveForm.address = searchInputV;

        //关闭对话框
        this.dialogVisable = false;
      },
      selectAdrress(){
        this.dialogVisable = true;
        this.keyword2='';//每次打开都要求清空地图上的地址
        //document.getElementById("searchInput").value=''
      },

      rowDrawerClick(){

      },
      //计数用的
      handleChange(value) {
        console.log(value);
      },


		},
		mounted() {
		  //页面加载就调用这个方法
			this.getShops();
		}
	}

</script>
<!--百度地图的样式 不可少-->
<style lang="scss" scoped>

  .title {
    margin: 0px auto 40px auto;
    text-align: center;
    color: #505458;
  }
  .remember {
    margin: 0px 0px 35px 0px;
  }

.map {
  width: 100%;
  height: 300px;
}
.searchinput{
  width: 300px;
  box-sizing: border-box;
  padding: 9px;
  border: 1px solid #dddee1;
  line-height: 20px;
  font-size: 16px;
  height: 38px;
  color: #333;
  position: relative;
  border-radius: 4px;
}
</style>